package org.example.Interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.models.R;
import org.example.utils.JwtUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    ObjectMapper objectMapper=new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("token");
        if (token==null){
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            R r = R.error(401,"你还未登录，请重新登陆");
            String json = objectMapper.writeValueAsString(r);
            response.getWriter().print(json);
            return false;
        }
        try {
             JwtUtils.isExpired(token);
        } catch (Exception e) {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            R r = R.error(401,"令牌已经过期，请重新登陆");
            String json = objectMapper.writeValueAsString(r);
            response.getWriter().print(json);
            return false;
        }
        return true;
    }
}
